/*   
 * Copyright (c) 2011, TUgether, TU Braunschweig
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 
 /**
 * @author Mohamed Karray <mohamed.karray@gmx.de>
 *
 */
 

package de.tu_bs.tugether.liferayunit.util;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.log4j.HTMLLayout;
import org.apache.log4j.Logger;
import org.apache.log4j.WriterAppender;

import com.gargoylesoftware.htmlunit.html.HtmlBody;
import com.gargoylesoftware.htmlunit.html.HtmlPage;

import de.tu_bs.tugether.liferayunit.config.LiferayUnitConfigFolder;

public class LiferayUtil {
	
	public static WriterAppender appender ;
	public static Logger logger = Logger.getLogger("Liferay");
	@SuppressWarnings("rawtypes")
	private static Class properyClassFolder = LiferayUnitConfigFolder.class;

	@SuppressWarnings("rawtypes")
	public static Class getConfigFolder() {
		return properyClassFolder;
	}

	public static void activateLogger(String filename) {
		HTMLLayout layout = new HTMLLayout();

		appender = null;
		try {
			FileOutputStream output = new FileOutputStream(filename+".html");
			appender = new WriterAppender(layout, output);
		} catch (Exception e) {
			e.getStackTrace();
		}
		logger.addAppender(appender);
		
	}
	public static void setConfigFolderClass(@SuppressWarnings("rawtypes") Class properyClassFolder) {
		LiferayUtil.properyClassFolder = properyClassFolder;
		LiferayUtil.logger.debug("Config properyClassFolder change: "+ properyClassFolder);
	}

	static public InputStream getProprtyFile(String propertiesFileName) throws FileNotFoundException {
		
		InputStream resource = properyClassFolder.getResourceAsStream(propertiesFileName);
		if(resource == null){
			throw new FileNotFoundException("Properties - File: " + propertiesFileName);
		}
		return resource;
	}

	public static boolean isSignedIn(HtmlPage page) {
		HtmlBody body = (HtmlBody) page.getBody();
		String classAtr = body.getAttribute("class");
		return classAtr.contains("signed-in");
	}
	static public boolean equalsRegExp(String regExp, String input) {
		Pattern p = Pattern.compile(regExp,Pattern.CASE_INSENSITIVE);
		Matcher m = p.matcher(input);
		return m.find();
	}

	
}
